﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace IQReportes.Utils
{
    /// <summary>
    /// Validación de rango de longitud
    /// </summary>
    public class RangoLongitudAttribute:ValidationAttribute
    {
        /// <summary>
        /// longitud mínima
        /// </summary>
        private readonly int _minLength;
        /// <summary>
        /// longitud máxima
        /// </summary>
        private readonly int _maxLength;
        /// <summary>
        /// Constructor con parámetros
        /// </summary>
        /// <param name="minLength">longitud mínima</param>
        /// <param name="maxLength">longitud máxima</param>
        public RangoLongitudAttribute(int minLength, int maxLength) 
            : base("El campo {0} debe tener entre "+minLength + " y " + maxLength + " caracteres de longitud")
        {
            _minLength = minLength;
            _maxLength = maxLength;
        }
        /// <summary>
        /// validar campo
        /// </summary>
        /// <param name="value">campo</param>
        /// <param name="validationContext">contexto</param>
        /// <returns>éxito o error</returns>
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value != null)
            {
                var cadena = value.ToString();
                if (cadena.Length < _minLength || cadena.Length > _maxLength)
                {
                    var errorMessage = FormatErrorMessage(validationContext.DisplayName);
                    return new ValidationResult(errorMessage);
                }
            }
            return ValidationResult.Success;
        }   
    }
}